package com.company.jrlz.web.screens.devicestatus;

import com.company.jrlz.entity.Device;
import com.haulmont.cuba.gui.Notifications;
import com.haulmont.cuba.gui.components.HasValue;
import com.haulmont.cuba.gui.model.InstanceContainer;
import com.haulmont.cuba.gui.screen.*;
import com.company.jrlz.entity.DeviceStatus;

import javax.inject.Inject;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

@UiController("jrlz_DeviceStatus.edit")
@UiDescriptor("device-status-edit.xml")
@EditedEntityContainer("deviceStatusDc")
@LoadDataBeforeShow
public class DeviceStatusEdit extends StandardEditor<DeviceStatus> {
    @Inject
    private InstanceContainer<DeviceStatus> deviceStatusDc;
    @Inject
    private Notifications notifications;
    @Subscribe("deviceNameField")
    public void onDeviceNameFieldValueChange(HasValue.ValueChangeEvent<Device> event) {
        deviceStatusDc.getItemOrNull().setDeviceType(event.getValue().getDeviceType());
        deviceStatusDc.getItemOrNull().setLine(event.getValue().getLine());
    }




    @Subscribe
    public void onBeforeCommitChanges(BeforeCommitChangesEvent event) {
        String timeFormat = "yyyy-MM-dd HH:mm";
        if(getEditedEntity().getLastAlarmTime()!=null){
            boolean isValid1 = isValidDate(getEditedEntity().getLastAlarmTime(), timeFormat);
            if(!isValid1){
                notifications.create().withCaption("告警时间格式不正确！").show();
                event.preventCommit();
                return;
            }
        }
        if(getEditedEntity().getPowerOnTime()!=null){
            boolean isValid2 = isValidDate(getEditedEntity().getPowerOnTime(), timeFormat);
            if(!isValid2){
                notifications.create().withCaption("开机时间格式不正确！").show();
                event.preventCommit();
            }
        }
    }

    public boolean isValidDate(String dateStr, String format) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format); // 创建日期格式化对象
        try {
            LocalDate.parse(dateStr, dtf); // 尝试解析
            return true; // 如果解析成功，返回true
        } catch (DateTimeParseException e) {
            return false; // 如果解析抛出异常，返回false
        }
    }

}